package com.keson.autosetup;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.keson.autosetup.util.FileUtil;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private Handler handler;

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        System.out.println("??????????????????????" +getDpi());
        getPermission();

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                ((LinearLayout) findViewById(R.id.frame)).addView((TextView)msg.obj);
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 获取U盘目录
                String usbPath = null;
                String[] dir = new File("/storage/").list();
                if (dir.length != 3) {
                    TextView text = new TextView(MainActivity.this);
                    text.setText("未插入U盘，安装失败!");
                    text.setTextColor(Color.RED);
                    handler.sendMessage(handler.obtainMessage(100,text));
                    return;
                }
                for (String s : dir) {
                    if (!s.equals("emulated") && !s.equals("self")) {
                        usbPath = "/storage/" + s;
                        break;
                    }
                }


                // 拷贝视频文件
                TextView text1 = new TextView(MainActivity.this);
                text1.setText("开始复制视频文件。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                if (!new File(usbPath + "/eqplayer/Movies").exists()) {
                    TextView text = new TextView(MainActivity.this);
                    text.setText("U盘中未找到/eqplayer/Movies文件夹，复制视频失败!");
                    text.setTextColor(Color.RED);
                    handler.sendMessage(handler.obtainMessage(100,text));
                } else {
                    FileUtil.copyDirectiory(usbPath + "/eqplayer/Movies", Environment.getExternalStorageDirectory() + "/Movies");
                    TextView text = new TextView(MainActivity.this);
                    text.setText("复制视频文件完毕。");
                    text.setTextColor(Color.GREEN);
                    handler.sendMessage(handler.obtainMessage(100,text));
                }


                // 拷贝图片文件
                text1 = new TextView(MainActivity.this);
                text1.setText("开始复制图片文件。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                if (!new File(usbPath + "/eqplayer/Pictures").exists()) {
                    TextView text = new TextView(MainActivity.this);
                    text.setText("U盘中未找到/eqplayer/Pictures，复制图片失败!");
                    text.setTextColor(Color.RED);
                    handler.sendMessage(handler.obtainMessage(100,text));
                } else {
                    FileUtil.copyDirectiory(usbPath + "/eqplayer/Pictures", Environment.getExternalStorageDirectory() + "/Pictures");
                    TextView text = new TextView(MainActivity.this);
                    text.setText("复制图片文件完毕。");
                    text.setTextColor(Color.GREEN);
                    handler.sendMessage(handler.obtainMessage(100,text));
                }


//        复制配置文件
                text1 = new TextView(MainActivity.this);
                text1.setText("开始复制配置文件。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                if (new File(usbPath + "/eqplayer/centerConfig.properties").exists()) {
                    FileUtil.copyFile(new File(usbPath + "/eqplayer/centerConfig.properties"), new File(Environment.getExternalStorageDirectory() + "/centerConfig.properties"));
                }
                if (new File(usbPath + "/eqplayer/config.properties").exists()) {
                    FileUtil.copyFile(new File(usbPath + "/eqplayer/config.properties"), new File(Environment.getExternalStorageDirectory() + "/config.properties"));
                }
                if (new File(usbPath + "/eqplayer/info.properties").exists()) {
                    FileUtil.copyFile(new File(usbPath + "/eqplayer/info.properties"), new File(Environment.getExternalStorageDirectory() + "/info.properties"));
                }
                if (new File(usbPath + "/eqplayer/client1.ovpn").exists()) {
                    File f000 = new File(Environment.getExternalStorageDirectory() + "/.000/client1.ovpn");
                    if(!f000.getParentFile().exists()){
                        f000.getParentFile().mkdirs();
                    }
                    FileUtil.copyFile(new File(usbPath + "/eqplayer/client1.ovpn"), f000);
                }
                text1 = new TextView(MainActivity.this);
                text1.setText("复制配置文件完毕。");
                text1.setTextColor(Color.GREEN);
                handler.sendMessage(handler.obtainMessage(100,text1));


                //安装软件
                text1 = new TextView(MainActivity.this);
                text1.setText("开始安装讯飞语音+。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                if (new File(usbPath + "/eqplayer/com.iflytek.speechcloud_1.1.1045_112.apk").exists()) {
                    installApp(usbPath + "/eqplayer/com.iflytek.speechcloud_1.1.1045_112.apk");
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装讯飞语音+完毕。");
                    text1.setTextColor(Color.GREEN);
                    handler.sendMessage(handler.obtainMessage(100,text1));

                    try {

                        Intent intent = new Intent();
                        intent.setAction("com.android.settings.TTS_SETTINGS");
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        MainActivity.this.startActivity(intent);
                        Thread.sleep(4000);
                        if(getDpi()==160){
                            execRootCmd("input tap 105 236");
                            Thread.sleep(2000);
                            execRootCmd("input tap 869 998");
                        }else{
                            execRootCmd("input tap 156 356");
                            Thread.sleep(2000);
                            execRootCmd("input tap 886 1047");
                        }
                        Thread.sleep(2000);
                        execRootCmd("am force-stop com.android.settings");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                } else {
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装讯飞语音+失败，未找到安装文件。");
                    text1.setTextColor(Color.RED);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                }

                text1 = new TextView(MainActivity.this);
                text1.setText("开始安装清清理。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                if (new File(usbPath + "/eqplayer/app-release_legu_signed-130301-o_1d6fvv13b4ov10281po81g8o6gcq-uid-755105.apk").exists()) {
                    installApp(usbPath + "/eqplayer/app-release_legu_signed-130301-o_1d6fvv13b4ov10281po81g8o6gcq-uid-755105.apk");
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装清清理完毕。");
                    text1.setTextColor(Color.GREEN);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                } else {
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装清清理失败，未找到安装文件。");
                    text1.setTextColor(Color.RED);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                }

                text1 = new TextView(MainActivity.this);
                text1.setText("开始安装防火墙。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                if (new File(usbPath + "/eqplayer/com.jtschohl.androidfirewall.apk").exists()) {
                    installApp(usbPath + "/eqplayer/com.jtschohl.androidfirewall.apk");
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装防火墙完毕。");
                    text1.setTextColor(Color.GREEN);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                } else {
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装防火墙失败，未找到安装文件。");
                    text1.setTextColor(Color.RED);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                }

                text1 = new TextView(MainActivity.this);
                text1.setText("开始安装钛备份。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                if (new File(usbPath + "/eqplayer/com.keramidas.TitaniumBackup_8.3.2_413.apk").exists()) {
                    installApp(usbPath + "/eqplayer/com.keramidas.TitaniumBackup_8.3.2_413.apk");
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装钛备份完毕。");
                    text1.setTextColor(Color.GREEN);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                } else {
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装钛备份失败，未找到安装文件。");
                    text1.setTextColor(Color.RED);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                }

                text1 = new TextView(MainActivity.this);
                text1.setText("开始安装文本编辑器。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                if (new File(usbPath + "/eqplayer/jp.sblo.pandora.jota_0.2.39_89.apk").exists()) {
                    installApp(usbPath + "/eqplayer/jp.sblo.pandora.jota_0.2.39_89.apk");
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装文本编辑器完毕。");
                    text1.setTextColor(Color.GREEN);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                } else {
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装文本编辑器失败，未找到安装文件。");
                    text1.setTextColor(Color.RED);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                }

//        text1 = new TextView(this);
//        text1.setText("开始安装向日葵。");
//        handler.sendMessage(handler.obtainMessage(100,text1));
//        if (new File(usbPath + "/eqplayer/SunloginClient_3.10.18.22581.apk").exists()) {
//            installApp(usbPath + "/eqplayer/SunloginClient_3.10.18.22581.apk");
//            text1 = new TextView(this);
//            text1.setText("安装向日葵完毕。");
//            handler.sendMessage(handler.obtainMessage(100,text1));
//            text1.setTextColor(Color.GREEN);
//        } else {
//            text1 = new TextView(this);
//            text1.setText("安装向日葵失败，未找到安装文件。");
//            handler.sendMessage(handler.obtainMessage(100,text1));
//            text1.setTextColor(Color.RED);
//        }

                text1 = new TextView(MainActivity.this);
                text1.setText("开始安装远程支持。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                if (new File(usbPath + "/eqplayer/de.blinkt.openvpn_168.apk").exists()) {
                    installApp(usbPath + "/eqplayer/de.blinkt.openvpn_168.apk");
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装远程支持完毕。");
                    handler.sendMessage(handler.obtainMessage(100,text1));
                    text1.setTextColor(Color.GREEN);
                } else {
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装远程支持失败，未找到安装文件。");
                    handler.sendMessage(handler.obtainMessage(100,text1));
                    text1.setTextColor(Color.RED);
                }

                text1 = new TextView(MainActivity.this);
                text1.setText("开始安装ARDC。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                if (new File(usbPath + "/eqplayer/com.he.ardcV4.0.1655.apk").exists()) {
                    installApp(usbPath + "/eqplayer/com.he.ardcV4.0.1655.apk");
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装ARDC完毕。");
                    handler.sendMessage(handler.obtainMessage(100,text1));
                    text1.setTextColor(Color.GREEN);
                } else {
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装ARDC失败，未找到安装文件。");
                    handler.sendMessage(handler.obtainMessage(100,text1));
                    text1.setTextColor(Color.RED);
                }

                text1 = new TextView(MainActivity.this);
                text1.setText("开始配置开发者选项。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                try {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
                    startActivity(intent);
                    Thread.sleep(4000);
                    if(getDpi()==160){
                        execRootCmd("input tap 290 320");
                    }else{
                        execRootCmd("input tap 385 484");
                    }
                    Thread.sleep(2000);
                    execRootCmd("am force-stop com.android.settings");
                    text1 = new TextView(MainActivity.this);
                    text1.setText("开发者选项配置完毕。");
                    text1.setTextColor(Color.GREEN);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    text1 = new TextView(MainActivity.this);
                    text1.setText("开发者选项配置失败。");
                    text1.setTextColor(Color.GREEN);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                }

                text1 = new TextView(MainActivity.this);
                text1.setText("开始安装预警软件。");
                handler.sendMessage(handler.obtainMessage(100,text1));
                if (new File(usbPath + "/eqplayer/app-release.apk").exists()) {
//                    execRootCmd("mount -o remount /system");
//                    execRootCmd("cp "+usbPath + "/eqplayer/app-release.apk /system/app");
                    installApp(usbPath + "/eqplayer/app-release.apk");
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装预警软件完毕。");
                    text1.setTextColor(Color.GREEN);
                    handler.sendMessage(handler.obtainMessage(100,text1));

                    execRootCmd("am start -n com.keson.eq/.MainActivity");

//                    text1 = new TextView(MainActivity.this);
//                    text1.setText("安装准备重启。");
//                    text1.setTextColor(Color.RED);
//                    handler.sendMessage(handler.obtainMessage(100,text1));
//                    for (int i = 5; i > 0; i--) {
//                        try {
//                            Thread.sleep(1000);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                        text1 = new TextView(MainActivity.this);
//                        text1.setText(i+"");
//                        text1.setTextColor(Color.RED);
//                        handler.sendMessage(handler.obtainMessage(100,text1));
//                    }
//                    execRootCmd("reboot");
                } else {
                    text1 = new TextView(MainActivity.this);
                    text1.setText("安装预警软件失败，未找到安装文件。");
                    text1.setTextColor(Color.RED);
                    handler.sendMessage(handler.obtainMessage(100,text1));
                }
//                MainActivity.this.finish();
            }
        }).start();
    }



    public static void installApp(final String mPath){
        execRootCmd("pm install -r " + mPath);
    }

    /**
     * 执行命令并且输出结果
     */
    public static String execRootCmd(String cmd) {
        String result = "";
        DataOutputStream dos = null;
        DataInputStream dis = null;

        try {
            Process p = Runtime.getRuntime().exec("su");
            dos = new DataOutputStream(p.getOutputStream());
            dis = new DataInputStream(p.getInputStream());

//            Log.i(TAG, cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            String line = null;
            while ((line = dis.readLine()) != null) {
//                Log.d("result", line);
                result += line;
            }
            p.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public void getPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET
                    ,Manifest.permission.ACCESS_WIFI_STATE
                    ,Manifest.permission.CHANGE_WIFI_STATE
                    ,Manifest.permission.MOUNT_FORMAT_FILESYSTEMS
                    ,Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ,Manifest.permission.READ_EXTERNAL_STORAGE
                    ,Manifest.permission.READ_LOGS
                    ,Manifest.permission.WAKE_LOCK
                    ,Manifest.permission.RECEIVE_BOOT_COMPLETED
                    ,Manifest.permission.WRITE_SETTINGS
                    ,Manifest.permission.WRITE_SECURE_SETTINGS
                    ,Manifest.permission.SET_TIME
                    ,Manifest.permission.SYSTEM_ALERT_WINDOW
                    ,Manifest.permission.CAMERA
                    ,Manifest.permission.RECORD_AUDIO
                    ,Manifest.permission.ACCESS_NETWORK_STATE
                    ,Manifest.permission.REORDER_TASKS}, 1);
        }
    }

    private float getDpi() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.densityDpi;
    }
}
